import time

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from flask_cors import CORS
from flask import Flask, request, json
import logging
from logging.handlers import RotatingFileHandler

app = Flask('51tracking-awb-service')
CORS(app)

logging.basicConfig(level=logging.INFO)
handler = RotatingFileHandler('51tracking.log', maxBytes=10000, backupCount=1)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
app.logger.addHandler(handler)


def createChromeDriver():
    chrome_options = webdriver.ChromeOptions()
    chrome_options.add_argument('--headless')
    chrome_options.add_argument('--no-sandbox')
    chrome_options.add_argument('--disable-dev-shm-usage')

    # 将--user-data-dir改为自定义目录
    # 在linux服务器上执行，需要增加
    # chrome_options.add_argument("--user-data-dir=/root/51tracking-awb")
    # s = Service(executable_path='/usr/local/bin/chromedriver')

    s = Service(executable_path='/Users/gilbert/chromedriver-mac-x64/chromedriver')
    _chrome_driver_instance = webdriver.Chrome(service=s, options=chrome_options)

    _chrome_driver_instance.maximize_window()

    return _chrome_driver_instance


def scrapyAwbInfo(awb):
    chrome_driver_instance = createChromeDriver()

    try:
        chrome_driver_instance.get("https://www.51tracking.com/aircargo/cn/" + str(awb))

        time.sleep(30)

        try:
            invalid = chrome_driver_instance.find_element(By.XPATH,
                                                          "//span[contains(text(), '跟踪单号尚未提供查询支持')]")
            if invalid:
                rst = {
                    "error": "NOT SUPPORT",
                    "result": "FAILED"
                }

                app.logger.info("AWB " + awb + " " + rst.__str__())

                return rst
        except Exception as e:
            e.__str__()
            pass

        try:
            invalid = chrome_driver_instance.find_element(By.XPATH,
                                                          "//span[contains(text(), '单号查询不到跟踪信息')]")
            if invalid:
                rst = {
                    "error": "NOT SUPPORT",
                    "result": "FAILED"
                }

                app.logger.info("AWB " + awb + " " + rst.__str__())

                return rst
        except Exception as e:
            e.__str__()
            pass

        flightNo = ''
        source = ''
        destination = ''
        scheduleDepartureTime = ''
        estimatedArrivalTime = ''
        departureTime = ''
        arrivalTime = ''
        weight = ''
        pcs = ''
        try:
            flightNo = chrome_driver_instance.find_element(By.XPATH,
                                                           "//tbody[tr[1]/td[1]='航班']/tr[2]/td[1]").text
            source = chrome_driver_instance.find_element(By.XPATH,
                                                         "//tbody[tr[1]/td[2]='出发站']/tr[2]/td[2]").text
            destination = chrome_driver_instance.find_element(By.XPATH,
                                                              "//tbody[tr[1]/td[3]='到达站']/tr[2]/td[3]").text
            scheduleDepartureTime = chrome_driver_instance.find_element(By.XPATH,
                                                                        "//tbody[tr[1]/td[4]='预离时间']/tr[2]/td[4]").text
            estimatedArrivalTime = chrome_driver_instance.find_element(By.XPATH,
                                                                       "//tbody[tr[1]/td[5]='预抵时间']/tr[2]/td[5]").text
            departureTime = chrome_driver_instance.find_element(By.XPATH,
                                                                "//tbody[tr[1]/td[6]='起飞时间']/tr[2]/td[6]").text
            arrivalTime = chrome_driver_instance.find_element(By.XPATH,
                                                              "//tbody[tr[1]/td[7]='抵达时间']/tr[2]/td[7]").text
            weight = chrome_driver_instance.find_element(By.XPATH,
                                                         "//tbody[tr[1]/td[8]='重量']/tr[2]/td[8]").text
            pcs = chrome_driver_instance.find_element(By.XPATH,
                                                      "//tbody[tr[1]/td[9]='件']/tr[2]/td[9]").text
        except Exception as e:
            e.__str__()
            pass

        if flightNo == '':
            source = chrome_driver_instance.find_element(By.XPATH,
                                                         "//tbody[tr[1]/td[1]='始发站']/tr[2]/td[1]").text
            destination = chrome_driver_instance.find_element(By.XPATH,
                                                              "//tbody[tr[1]/td[2]='目的站']/tr[2]/td[2]").text
            weight = chrome_driver_instance.find_element(By.XPATH,
                                                         "//tbody[tr[1]/td[3]='重量']/tr[2]/td[3]").text
            pcs = chrome_driver_instance.find_element(By.XPATH,
                                                      "//tbody[tr[1]/td[4]='件']/tr[2]/td[4]").text

        details = chrome_driver_instance.find_elements(By.XPATH, "//tbody[tr[1]/td[1]='状态']"
                                                                 "/tr[@class='h-b-e']/td")
        resp = []
        i = 0
        while i < len(details):
            if len(flightNo) == 0 and len(details[i + 4].text) > 1:
                flightNo = details[i + 4].text

            resp.append({
                "status": details[i].text,
                "time": details[i + 1].text,
                "event": details[i + 2].text,
                "location": details[i + 3].text,
                "weight": details[i + 5].text,
                "pcs": details[i + 6].text
            })

            i = i + 9

        respRst = {
            "result": "SUCCESS",
            "data": {
                "summary": {
                    "flightNo": flightNo,
                    "source": source,
                    "destination": destination,
                    "scheduledDepartureTime": scheduleDepartureTime,
                    "estimatedArrivalTime": estimatedArrivalTime,
                    "departureTime": departureTime,
                    "arrivalTime": arrivalTime,
                    "weight": weight,
                    "pcs": pcs
                },
                "details": resp
            }
        }

        app.logger.info("AWB " + awb + " " + respRst.__str__())

        return respRst

    except Exception as e:
        app.logger.error("AWB " + awb + " " + e.__str__())
        return {
            "result": "FAILED",
            "error": "LOADING IN-COMPLETED"
        }
    finally:
        chrome_driver_instance.quit()


@app.route('/getAwbInfo', methods=['POST'])
def getAwbInfo():
    data = json.loads(json.dumps(request.get_json()))

    return scrapyAwbInfo(data['awb'])


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=10010, debug=False)
